package com.shortlink.common.interceptor;


import com.shortlink.common.constants.RedisConstant;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RequiredArgsConstructor
public class BlackListInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String clientIP = request.getRemoteAddr();
        String key= RedisConstant.BLACKLIST_KEY_PREFIX +clientIP;

        // 检查黑名单
        if (stringRedisTemplate.hasKey(key)) {
            response.getWriter().write("Your IP is blacklisted.");
            return false;
        }

        return true;
    }

}
